package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"syscall"
)

func main() {

	// 创建新文件
	// writeNewFile()

	// 追加内容
	// appendOldFile()

	// 读取后追加
	// readAndAppendOldFile()

	// ioutil简单拷贝
	// simpleCopy()

	// io拷贝
	// written, err := ioCopy("D:/tmp/SuperPuTTY.7z", "D:/tmp/SuperPuTTY1.7z")
	// fmt.Println(written, err)
}

func writeNewFile() {

	file, err := os.OpenFile("d:/log/test.log", syscall.O_CREAT|syscall.O_WRONLY, 0666)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return
	}

	defer file.Close()

	writer := bufio.NewWriter(file)

	for i := 0; i < 5; i++ {

		_, err := writer.WriteString("hello world\n")

		if err != nil {
			fmt.Printf("Write file error: %v\n", err)
		}
	}

	_ = writer.Flush()
}

func appendOldFile() {

	file, err := os.OpenFile("d:/log/test.log", syscall.O_APPEND|syscall.O_WRONLY, 0666)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return
	}

	defer file.Close()

	writer := bufio.NewWriter(file)

	for i := 0; i < 5; i++ {

		_, err := writer.WriteString("xuguofeng 2021\n")

		if err != nil {
			fmt.Printf("Write file error: %v\n", err)
		}
	}

	_ = writer.Flush()
}

func readAndAppendOldFile() {

	file, err := os.OpenFile("d:/log/test.log", syscall.O_APPEND|syscall.O_RDWR, 0666)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return
	}

	defer file.Close()

	// 先读文件
	reader := bufio.NewReader(file)

	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		fmt.Print(line)
	}

	// 再追加内容
	writer := bufio.NewWriter(file)

	for i := 0; i < 5; i++ {
		_, err := writer.WriteString("new line\n")
		if err != nil {
			fmt.Printf("Write file error: %v\n", err)
		}
	}

	_ = writer.Flush()
}

func simpleCopy() {

	bytes, err := ioutil.ReadFile("d:/log/test.log")

	if err != nil {
		fmt.Printf("Read file error: %v\n", err)
		return
	}

	_ = ioutil.WriteFile("d:/log/test1.log", bytes, syscall.O_CREAT|syscall.O_RDWR)
}

func ioCopy(srcFilename string, destFilename string) (written int64, err error) {

	// 打开源文件
	srcFile, err := os.Open(srcFilename)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return 0, err
	}

	// 关闭源文件
	defer srcFile.Close()

	// 打开目标文件
	destFile, err := os.OpenFile(destFilename, os.O_WRONLY|os.O_CREATE, 0666)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return 0, err
	}

	// 关闭目标文件
	defer destFile.Close()

	// 创建流
	reader := bufio.NewReader(srcFile)
	writer := bufio.NewWriter(destFile)

	// 如果不写，会丢失字节
	defer writer.Flush()

	// 拷贝
	return io.Copy(writer, reader)
}
